package com.yuantu.judiciary.serviceimpl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yuantu.judiciary.dao.ICaseRemoveDao;
import com.yuantu.judiciary.dao.IOrgVipRecordDao;
import com.yuantu.judiciary.dao.IQueryRecordDao;
import com.yuantu.judiciary.exception.ServiceException;
import com.yuantu.judiciary.model.domain.QueryEntityDO;
import com.yuantu.judiciary.model.domain.QueryRecordDO;
import com.yuantu.judiciary.model.dto.*;
import com.yuantu.judiciary.model.enums.AuthResultType;
import com.yuantu.judiciary.model.enums.CaseCategory;
import com.yuantu.judiciary.model.enums.QueryType;
import com.yuantu.judiciary.model.vo.PageVO;
import com.yuantu.judiciary.model.vo.ShopThirdQueryVO;
import com.yuantu.judiciary.service.ICheckPersonService;
import com.yuantu.judiciary.service.ICheckResultService;
import com.yuantu.judiciary.service.IShopCheckService;
import com.yuantu.judiciary.utils.DESUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * 组织管理模块
 *
 * @author syw
 * @since 2023-08-12
 **/
@Service
@RequiredArgsConstructor
public class ShopCheckServiceImpl implements IShopCheckService {

    @Resource
    IQueryRecordDao queryRecordDao;

    @Resource
    ICaseRemoveDao caseRemoveDao;

    @Resource
    IOrgVipRecordDao orgVipRecordDao;
    private final ICheckResultService checkResultService;
    private final ICheckPersonService checkPersonService;


    @Override
    public ShopThirdQueryVO getThirdQueryByIdenitityNum(String token, String identityNum) {
        if(token.isEmpty()){
            throw new ServiceException(990301, "请求头未包含token字段或token字段为空");
        }
        String tokenJson = DESUtil.decrypt("a4052b5cf",token);
        JSONObject tokenJsonO = JSONObject.parseObject(tokenJson);
        long currentTimestamp = Instant.now().getEpochSecond();
        if(currentTimestamp - tokenJsonO.getLong("timestamp") > 300){
            throw new ServiceException(990302, "token已失效，请重新生成");
        }
        if(!(tokenJsonO.getString("username").equals("thirdV1")&&tokenJsonO.getString("password").equals("k7e^b9m@z4!d"))){
            throw new ServiceException(990303, "用户名或密码错误");
        }
        List<QueryRecordDO> list = queryRecordDao.findByContentContaining(identityNum);
        if(list.isEmpty()){
            throw new ServiceException(990304, "未找到背调记录");
        }
        QueryRecordDO queryRecord = list.get(0);
        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        Long userId = 28474L;
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
        String badRecordStr = checkResultService.getJsonDataProd(userId, QueryType.PER_BAD_RECORD, searchRecord, entity);
        String judicialStr = checkResultService.getJsonDataProd(userId, QueryType.PER_JUDICIAL, searchRecord, entity);
        ResBadRecordDTO personResult = null;
        if (!StringUtils.isBlank(badRecordStr)) {
            List<ResBadRecordDTO> data = JSON.parseArray(badRecordStr, ResBadRecordDTO.class);
            personResult = data.get(0);
        }
        ResJudicialDataProdDTO judicialResult = null;
        if (!StringUtils.isBlank(judicialStr)) {
            List<ResJudicialDataProdDTO> data = JSON.parseArray(judicialStr, ResJudicialDataProdDTO.class);
            judicialResult = data.get(0);
        }

        List<CaseDataDTO> criminalInfos = new ArrayList<>();
        List<CaseDataDTO> civilInfos = new ArrayList<>();
        List<CaseDataDTO> administrativeInfos = new ArrayList<>();
        List<CaseDataDTO> preservationInfos = new ArrayList<>();
        List<CaseDataDTO> implementInfos = new ArrayList<>();
        List<CaseDataDTO> bankruptInfos = new ArrayList<>();
        List<CaseDataDTO> jurisdictionInfos = new ArrayList<>();
        List<CaseDataDTO> compensateInfos = new ArrayList<>();
        List<DishonestDataDTO> dishonestInfos = new ArrayList<>();
        List<LimitHighDataDTO> limitHighInfos = new ArrayList<>();
        int totalCase = 0;
        int criminalCase = 0;
        int civilCase = 0;
        int administrativeCase = 0;
        int preservationCase = 0;
        int implementCase = 0;
        int bankruptCase = 0;
        int jurisdictionCase = 0;
        int compensateCase = 0;
        int dishonestCase = 0;
        int limitHighCase = 0;
        if (judicialResult != null) {
            Map<String, List<CaseDataDTO>> detailMap = judicialResult.getCaseData();
            criminalInfos = detailMap.get(CaseCategory.CRIMINAL.getCode());
            civilInfos = detailMap.get(CaseCategory.CIVIL.getCode());
            administrativeInfos = detailMap.get(CaseCategory.ADMINISTRATIVE.getCode());
            preservationInfos = detailMap.get(CaseCategory.PRESERVATION.getCode());
            implementInfos = detailMap.get(CaseCategory.IMPLEMENT.getCode());
            bankruptInfos = detailMap.get(CaseCategory.BANKRUPT.getCode());
            jurisdictionInfos = detailMap.get(CaseCategory.JURISDICTION.getCode());
            compensateInfos = detailMap.get(CaseCategory.COMPENSATE.getCode());
            totalCase = criminalInfos.size() + civilInfos.size() + administrativeInfos.size() + preservationInfos.size() +
                    implementInfos.size() + bankruptInfos.size() + jurisdictionInfos.size() + compensateInfos.size();
            criminalCase = criminalInfos.size();
            civilCase = civilInfos.size();
            administrativeCase = administrativeInfos.size();
            preservationCase = preservationInfos.size();
            implementCase = implementInfos.size();
            bankruptCase = bankruptInfos.size();
            jurisdictionCase = jurisdictionInfos.size();
            compensateCase = compensateInfos.size();
            ResDishonestDataDTO sx = judicialResult.getSx();
            dishonestInfos = Optional.ofNullable(sx).map(ResDishonestDataDTO::getSxbzxr_current).orElse(new ArrayList<>());
            ResLimitDataDTO xg = judicialResult.getXg();
            limitHighInfos = Optional.ofNullable(xg).map(ResLimitDataDTO::getXgbzxr_current).orElse(new ArrayList<>());
            limitHighCase = limitHighInfos.size();
            dishonestCase = dishonestInfos.size();
            totalCase = totalCase + limitHighCase + dishonestCase;
        }
        ShopThirdQueryVO shopThirdQueryVO = new ShopThirdQueryVO();
        String risk = personResult == null ? "无风险" : (StringUtils.isBlank(personResult.getRisk()) ? "无风险" : personResult.getRisk());
        shopThirdQueryVO.setRiskLevel(risk);
        shopThirdQueryVO.setCriminalCaseCount(criminalCase);
        shopThirdQueryVO.setCivilCaseCount(civilCase);
        shopThirdQueryVO.setLimitHighConsumptionRecordCount(limitHighCase);
        shopThirdQueryVO.setAdministrativeCaseCount(administrativeCase);
        shopThirdQueryVO.setNonLitigationPreservationCaseCount(preservationCase);
        shopThirdQueryVO.setEnforcementCaseCount(implementCase);
        shopThirdQueryVO.setRiskRecordCount(dishonestCase);
        shopThirdQueryVO.setLimitHighConsumptionRecordCount(limitHighCase);
        return shopThirdQueryVO;
    }

}
